package org.lex.elec.model.dao.impl.mariadb;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

import org.lex.elec.model.AppException;
import org.lex.elec.model.ErrorCode;
import org.lex.elec.model.dao.BaseDao;
import org.lex.elec.model.dao.CableDao;
import org.lex.elec.model.dao.CableResultSetHandler;
import org.lex.elec.model.domain.Cable;

public class CableDaoImpl extends BaseDao<Cable> implements CableDao {
	private static final String TABLE_NAME = "cable";
	private static final CableResultSetHandler handler = new CableResultSetHandler();

	public CableDaoImpl(Connection conn) {
		super(conn);
	}

	@Override
	public Cable findById(int id) throws AppException {
		String sql = "select * from " + TABLE_NAME + " t where t.id=?";
		try {
			return this.singleResult(this.getQueryRunner().query(this.getConnection(), sql, handler, id));
		} catch (SQLException e) {
			throw new AppException(ErrorCode.DB_READ_ERROR, "db query error on finding Cable[id=" + id + "]", e);
		}
	}

	@Override
	public List<Cable> findByName(String name, boolean usingLike) throws AppException {
		Objects.requireNonNull(name, "name can't be null");
		StringBuilder sql = new StringBuilder("select * from " + TABLE_NAME + " t where t.name ");
		if (true == usingLike) {
			sql.append(" like '%?%'");
		} else {
			sql.append("=?");
		}
		try {
			return this.getQueryRunner().query(this.getConnection(), sql.toString(), handler, name);
		} catch (SQLException e) {
			throw new AppException(ErrorCode.DB_READ_ERROR, "db query error on finding Cable[name=(" + name
					+ "), usingLike=" + usingLike + "]", e);
		}
	}

	@Override
	public List<Cable> findByModel(String model, boolean usingLike) throws AppException {
		Objects.requireNonNull(model, "model can't be null");
		StringBuilder sql = new StringBuilder("select * from " + TABLE_NAME + " t where t.model ");
		if (true == usingLike) {
			sql.append(" like %?%");
		} else {
			sql.append("=?");
		}
		try {
			return this.getQueryRunner().query(this.getConnection(), sql.toString(), handler, model);
		} catch (SQLException e) {
			throw new AppException(ErrorCode.DB_READ_ERROR, "db query error on finding Cable[model=(" + model
					+ "), usingLike=" + usingLike + "]", e);
		}
	}
}
